//
//  HomeTableViewController.swift
//  SinaWeibo
//
//  Created by NeXTSTEP on 15/9/29.
//  Copyright © 2015年 NeXTSTEP. All rights reserved.
//

import UIKit

class HomeTableViewController: BaseTableViewController {
    
    private let statusCellIndentifier = "HomeCell"
    
    var statusCell: StatusCell?
    
    var selectedIndexPath: NSIndexPath?
    
    private lazy var presentIconView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = UIViewContentMode.ScaleAspectFill
//        iv.clipsToBounds = true
        return iv
    }()
    
    var statuses: [Status]? {
        didSet{
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        vistorLoginView?.setUpWithInfo("关注一些人，回这里看看有什么惊喜", iconName: "visitordiscover_feed_image_house",isHome:true)
        if userLogin {
            loadData()
        }
        
        //注册选中图片的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "selectPicture:", name: WBStatusCellSelectPictureNotification, object: nil)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func selectPicture(notification: NSNotification){
        print(notification)
        guard let urls = notification.userInfo?[WBStatusCellSelectPictureURLKey] as? [NSURL] else{
            print("URL数组不存在")
            return
        }
        
        guard let indexPath = notification.userInfo?[WBStatusCellSelectPictureIndexKey] as? NSIndexPath else {
            print("IndexPath不存在")
            return
        }
        
        guard let s = notification.object as? StatusCell else {
            print("图像视图不存在")
            return
        }
        
        self.statusCell = s
        self.selectedIndexPath = indexPath
        self.presentIconView.sd_setImageWithURL(urls[indexPath.item])
        
        let vc = PhotoBrowserViewController(urls: urls, index: indexPath.item)
        //设置转场代理
        vc.transitioningDelegate = self
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        
        presentViewController(vc, animated: true, completion: nil)
        
    }
    
    

    
    private func loadData(){
        Status.loadStatus { (statuses) -> () in
            self.statuses = statuses
        }
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(statusCellIndentifier) as! StatusCell
        
        cell.status = statuses![indexPath.row]
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let cell = tableView.dequeueReusableCellWithIdentifier(statusCellIndentifier) as! StatusCell
        let status = statuses![indexPath.row]
        return cell.rowHeight(status)
    }
    
    private var isPresented = false
}


extension HomeTableViewController: UIViewControllerTransitioningDelegate {
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = true
        return self
    }
    
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = false
        return self
    }
}

extension HomeTableViewController: UIViewControllerAnimatedTransitioning {
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.3
    }
    
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        if isPresented {
            let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
            let fromRect = statusCell!.cellFrameInSrceen(selectedIndexPath!)
            let toRect = statusCell!.cellFullFrameInScreen(selectedIndexPath!)
            self.presentIconView.frame = fromRect
            transitionContext.containerView()?.addSubview(self.presentIconView)

            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                self.presentIconView.frame = toRect
                }) { (_) -> Void in
                    self.presentIconView.removeFromSuperview()
                    transitionContext.containerView()?.addSubview(toView)
                    transitionContext.completeTransition(true)
            }
            return
        }
        
        let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! PhotoBrowserViewController
        let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
        let iv = fromVC.currentImageView()
        //累加父视图的形变
        let scale = fromView.transform.a
        iv.transform = CGAffineTransformScale(iv.transform, scale, scale)
        iv.center = fromView.center
        //将图像视图 添加到容器视图
        transitionContext.containerView()?.addSubview(iv)
        fromView.removeFromSuperview()
        let indexPaht = fromVC.currentImageIndex()

        let toRect = statusCell!.cellFrameInSrceen(indexPaht)
        
        UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
//            fromView.alpha = 0
            // 修改目标位置
            iv.frame = toRect
            }) { (_) -> Void in
                iv.removeFromSuperview()
                transitionContext.completeTransition(true)
                
        }
        
    }
    
    
        
}
